package com.huluobo.user

import android.util.Log
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.huluobo.user.entity.ApproveEntityItem
import java.lang.Exception

/**
 *  Created by LC on 2025/8/2.
 *  Paging数据源
 */
class ApprovePagingSource(private val userRepo: UserRepo) : PagingSource<Int, ApproveEntityItem>() {
    private var sum = 0
    override fun getRefreshKey(state: PagingState<Int, ApproveEntityItem>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ApproveEntityItem> {
        return try {
            //当前的页码,如果为空就是1,不为空就是key
            val currentPage = params.key ?: 1
            //当前请求数据的长度
            val size = 10
            //发起请求,产生返回
            val response = userRepo.getApprovePage(currentPage.toString(), size.toString())
            //从返回中提取数据源
            val items = response.data

            sum += items.size
            Log.e("TagA", "pagingSize:$sum:")

            //向前翻页的页码,必须判断是否大于1才能向前翻页
            val preKey = if (currentPage > 1) currentPage - 1 else null
            //向后翻页的页码,必须判断数据源中是否还有值,如果没有证明数据已经为空,向后翻页没有意义
            val nextKey = if (items.isNotEmpty()) currentPage + 1 else null
            LoadResult.Page(items, preKey, nextKey)
        } catch (e: Exception) {
            Log.e("TagA", "paging error:${e.message}")
            LoadResult.Error(e)
        }
    }
}